package com.net.xpay.common.service.impl.admin.rbac;

import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.net.xpay.common.domain.admin.rbac.Menu;
import com.net.xpay.common.domain.admin.rbac.Permission;
import com.net.xpay.common.manager.admin.rbac.MenuManager;
import com.net.xpay.common.manager.admin.rbac.PermissionManager;
import com.net.xpay.common.service.admin.rbac.PermissionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 2019/11/19 15:13

 */
@Slf4j
@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionManager permissionManager;

    @Autowired
    private MenuManager menuManager;

    /**
     * 根据管理员id返回管理员的所有权限集合
     *
     * @param adminUserId 管理员id
     * @return 权限集合
     */
    @Override
    public List<Permission> findByAdminUserId(Long adminUserId) {
        Preconditions.checkArgument(adminUserId != null);
        //权限表查出来的
        List<Permission> permissions = permissionManager.findByAdminUserId(adminUserId);

        //菜单表查出来的
        List<Permission> menuPermissions = findPermissionFromMenu(adminUserId);
        permissions.addAll(menuPermissions);
        return permissions;
    }

    private List<Permission> findPermissionFromMenu(Long adminUserId) {
        //该管理员所有的菜单
        List<Menu> menus = menuManager.findByAdminUserId(adminUserId);
        if (CollectionUtils.isEmpty(menus)) {
            return new ArrayList<>();
        }

        Set<String> permissions = new HashSet<>();
        for (Menu menu : menus) {
            if (Strings.isNullOrEmpty(menu.getPermissions())) {
                continue;
            }
            List<String> pms = Splitter.on(",").splitToList(menu.getPermissions());
            permissions.addAll(pms);
        }

        List<Permission> pms = new ArrayList<>();
        for (String p : permissions) {
            Permission permission = new Permission();
            permission.setName(p);
            pms.add(permission);
        }
        return pms;
    }
}
